Python cheat sheet

titile image

Background:

I have been using Python intensively for about 1 year. From now and then I look up some of the common operations and I decided to record all the code snippets in a handbook.

Table:

No. Goal Solution Note
1 Reverse a string or a list
def reverse(s):
return s[::-1]
 
2 Join a list of strings to a single string
def join(t):
return ''.join(t)
 
3 Flatten list from list of list
def flatten(t):
return [i for sub in t for i in sub]
# another implementation
def flatten(t):
return sum(t, [])
 
4 Trim a string
def trim(s):
return s.strip()
 
5 String replace a substring pattern with another substring
def replace(s, old, new):
return s.replace(old, new)
 
6 Cast float or string to int
def str2int(s):
return int(s)
auto floor to the nearest integer
7 Check string or char is in uppercase
def upper(s):
return s.isupper()
 
8 If statement in list comprehension
def neq0(t):
return [v for v in t if v != 0]
 
9 If else statement in list comprehension
def maskNone(t):
return [x if x else '' for x in t]
 
10 Transpose matrix (2-d array)
def transpose(m):
return [list(i) for i in zip(*m)]
 
11 Rotate matrix (2-d array) 90° clockwise
def rotate90(m):
return [list(i) for i in zip(*m[::-1])]
if you want to do it inplace, do:
matrix[:] = [list(i) for i in zip(*matrix[::-1])]
12 Check whether str1 is substring of str2
def substring(s, t):
return s in t
 
13 Get Current work directory
import os
print(os.getcwd())
 
14 Iterate dictionary
def iterate(d):
for k, v in d.items():
yield k, v
 
15 Split string with multiple delimiters
import re
re.split(',| |;', 'a; b d c,d, e, s')
 
16 Merge 2 dictionaries
from collections import Counter
a = Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})
b = Counter({'menu': 1, 'good': 1, 'bar': 3})
a.update(b)
new value is the sum of 2 values from 2 dictionaries
17 Initialize list with same primitive values
my_list = [True] * 400
don’t use this with 2-d array
18 Python supports tertiary operator
if 3 < 5 < 8:
print(5)
 
19 Sort a list of strings by length
my_list = ['cbc', 'a', 'bc', 'pbdc']
my_list.sort(key=len)
 
20 String split by keep the delimiters
import re
re.split('(;|,|\n)', 'He,llo * worl;d')
just add outer ( ) to the delimiters
21 Sort dictionary by values
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
if want to sort by keys, change itemgetter(1) to itemgetter(0)
22 Print 2-d array in a better format
import numpy as np
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
np.matrix(m)
 
23 Find index and last index of char in string
my_str = 'abcdefgb'
print(my_str.index('b'), my_str.rindex('b'))
 
24 Find index and last index of item in list
m = [1, 2, 3, 1, 4, 5]
print(m.index(1))
print(len(m) - 1 - m[::-1].index(1))
 
25 Automatically initialize for new key in dictionary
from collections import defaultdict
my_dict = defaultdict(int)
print(my_dict[4])
input of defaultdict should be callable, and takes no arguments
26 Get arbitrary one element from set
s = {8, 1, 2, 3}
next(iter(s))
 
27 Remove element at index 2 from the list
my_list = [1, 2, 3]
my_list.pop(2)
if no argument, last one is removed
28 Find locations (start, end) of matches with regular expression
import re
t = re.finditer('[A-Z][a-z]*', 'This Is My House')
print([i.span() for i in t])
 
29 Update each value in a dictionary with an operation
d = {1: 5, 3: 2, 0: 1}
d.update((k, d[k]**2) for k in d)
 
30 Find nth occurrence of b in string a
from functools import reduce
def findNth(a, b, n):
return reduce(lambda x, y: -1 if y > x + 1 else a.find(b, x + 1),
range(n), -1)
 
31 Find all indices of an element in a list
t = [1, 4, 2, 3, 4, 5]
print([i for i, x in enumerate(t) if x == 4])
 
32 Return a random element from a list
import random
t = [1, 4, 5]
print(random.choice(t))
 
33 Product of all elements of a list
from operator import mul
from functools import reduce
reduce(mul, [1, 2, 3, 4, 5, 10], 1)
 
34 Lexicographical  compare of strings
a, b = 'abc', 'bc'
print(a > b)
“abcd” > “ab” and “ad” > “ab”
35 Integer division
def int_division(a, b):
return a // b
round down
36 Two’s complement
print(~1345)
equals to -1315
37 Padding spaces to a string to a certain length
s = 'ab'
a = s.center(4)
b = s.ljust(5)
c = s.rjust(3)
print(a, b, c)
 
38 Get a random float
import random
random.random()
 
39 Get a random integer from range
import random
random.randrange(6)
 
40 Get profile of program, print out most time consuming function calls
import cProfile
cProfile.run('int(13)')
 
41 Get line by line time execution in jupyter notebook
import time
def sleep(n):
return time.sleep(n)
%load_ext line_profiler
%lprun -f sleep sleep(3)
need to specify the function name (e.g. totalNQueens) and the real execution call (e.g. totalNQueens(13))should use “” when passing strings as arguments
42 Usage of doctest
def average(values):
"""
>>> average([20, 30, 70])
40.0
"""
return sum(values) / len(values)
import doctest
doctest.testmod()
there must be at least 1 space on the right side of »>
43 Double-ended queue
from collections import deque
print(deque('cndota'))
can be think of a queue + stack
44 Printout nicely
from pprint import pprint
pprint({5: 3, 1: 4, 3: 0, 0: 8})
print out in sorted order
45 Permutation and combination
from itertools import combinations, permutations
list(combinations('123', 2)), list(permutations('123'))
output: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
46 Get all attributes and their values of an object
class duck:
def __init__(self):
self.age = 3
def quak(self):
print('ga')
d = duck()
vars(d)
 
47 Get the representation string of the object
repr(d)
if not specified, it will be like:’<main.Duck object at 0x00000133BDE7A6D8>’
48 Save memory by using generator instead of list
sum(x * x for x in range(7))
instead of sum([x*x for x in range(10)])
49 Variables created inside a loop are accessible outside the loop scope
for j in 3, 5:
print(j)
print(j)
thej actually is assigned the last element of the list mylist
50 Check whether a list iterate till end normally
for i in 3, 5:
if i == 4:
break
else:
print('no 4 in the list')
 
51 To make class objects comparable, just add function __lt__
class duck:
def __init__(self, n):
self.age = n
def __lt__(self, other):
return self.age < other.age
d = duck(3)
e = duck(5)
d < e
 
52 Sort a list of list by multiple values
import operator
s = [[1, 2], [1, 0], [2, 0]]
s.sort(key=lambda x: (x[0], x[1]))
 
Written on May 24, 2018